package com.podium.web.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.podium.auth.utils.SecurityUtils;
import com.podium.comment.AjaxResult;
import com.podium.comment.annotate.OperateLog;
import com.podium.comment.annotate.PermAuth;
import com.podium.comment.constant.OperateLogType;
import com.podium.comment.validation.groups.CreateGroup;
import com.podium.comment.validation.groups.UpdateGroup;
import com.podium.web.system.controller.dto.PasswordDto;
import com.podium.web.system.controller.dto.ResetPasswordDto;
import com.podium.web.system.entity.SysUser;
import com.podium.web.system.entity.SysUserRole;
import com.podium.web.system.service.SysUserRoleService;
import com.podium.web.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 邵文泽
 * @description 系统用户
 * @date Mon Apr 28 16:21:15 CST 2025
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 分页获取表系统用户信息
     *
     * @param sysUser 查询系统用户信息条件
     */
    @PermAuth("system:user:list")
    @GetMapping("page")
    public AjaxResult<IPage<SysUser>> getPage(@RequestParam(defaultValue = "1") int pageNum,
                                              @RequestParam(defaultValue = "10") int pageSize,
                                              SysUser sysUser
    ) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        return new AjaxResult<IPage<SysUser>>().success(sysUserService.page(page, sysUser));
    }

    /**
     * 获取表系统用户信息
     *
     * @param sysUser 查询系统用户信息条件
     */
    @PermAuth("system:user:list")
    @GetMapping("list")
    public AjaxResult<List<SysUser>> getList(SysUser sysUser) {
        return new AjaxResult<List<SysUser>>().success(sysUserService.list(sysUser));
    }

    /**
     * 根据ID获取系统用户信息
     */
    @GetMapping("{id}")
    public AjaxResult<SysUser> getByInfo(@PathVariable Long id) {
        return new AjaxResult<SysUser>().success(sysUserService.getById(id));
    }

    /**
     * 添加系统用户信息
     *
     * @param sysUser 系统用户信息
     */
    @OperateLog(title = "系统管理-用户管理", businessType = OperateLogType.ADD)
    @PermAuth("system:user:add")
    @PostMapping("/save")
    public AjaxResult<Void> save(@Validated(value = CreateGroup.class) @RequestBody SysUser sysUser) {
        boolean row = sysUserService.save(sysUser);
        return row ? new AjaxResult<Void>().success() : new AjaxResult<Void>().error();
    }

    /**
     * 更新系统用户信息
     *
     * @param sysUser 系统用户信息
     */
    @OperateLog(title = "系统管理-用户管理", businessType = OperateLogType.EDIT)
    @PermAuth("system:user:edit")
    @PostMapping("/update")
    public AjaxResult<Void> update(@Validated(value = UpdateGroup.class) @RequestBody SysUser sysUser) {
        boolean row = sysUserService.updateById(sysUser);
        return row ? new AjaxResult<Void>().success() : new AjaxResult<Void>().error();
    }

    /**
     * 管理员重置密码
     */
    @OperateLog(title = "系统管理-重置密码", businessType = OperateLogType.EDIT)
    @PostMapping("/resetPassword")
    public AjaxResult<Void> resetPassword(@Validated @RequestBody ResetPasswordDto resetPasswordDto) {
        SysUser sysUser = sysUserService.getById(resetPasswordDto.getUserId());
        if (sysUser == null) {
            return new AjaxResult<Void>().error("用户不存在！");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(resetPasswordDto.getPassword()));
        boolean row = sysUserService.updateById(sysUser);
        return row ? new AjaxResult<Void>().success() : new AjaxResult<Void>().error();
    }

    /**
     * 用户修改密码
     * @param passwordDto 修改密码信息
     */
    @OperateLog(title = "系统管理-修改密码", businessType = OperateLogType.EDIT)
    @PostMapping("/editPassword")
    public AjaxResult<Void> editPassword(@Validated @RequestBody PasswordDto passwordDto) {
        String password = SecurityUtils.getPassword();
        if (!SecurityUtils.matchesPassword(passwordDto.getOldPassword(), password)) {
            return new AjaxResult<Void>().error("旧密码错误！");
        }
        if (passwordDto.getOldPassword().equals(passwordDto.getNewPassword())) {
            return new AjaxResult<Void>().error("新密码不能与旧密码一致！");
        }
        if (!passwordDto.getNewPassword().equals(passwordDto.getConfirmPassword())){
            return new AjaxResult<Void>().error("两次输入的密码不一致！");
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(SecurityUtils.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(passwordDto.getNewPassword()));
        boolean row = sysUserService.updateById(sysUser);
        return row ? new AjaxResult<Void>().success() : new AjaxResult<Void>().error();
    }
    /**
     * 删除系统用户信息
     *
     * @param ids 系统用户信息ID集合
     */
    @OperateLog(title = "系统管理-用户管理", businessType = OperateLogType.DELETE)
    @PermAuth("system:user:delete")
    @GetMapping("/remove/{ids}")
    public AjaxResult<Void> remove(@PathVariable Long[] ids) {
        if (ids == null || ids.length == 0) {
            return new AjaxResult<Void>().error("没有要删除的数据！");
        }
        for (Long id : ids) {
            sysUserService.removeById(id);
        }
        return new AjaxResult<Void>().success();
    }

    /**
     * 根据用户ID获取角色ID
     * @param sysUserRole 用户角色关联信息
     */
    @PermAuth("system:user:allocation")
    @GetMapping("/listUserRole")
    public AjaxResult<List<SysUserRole>> listUserRole(SysUserRole sysUserRole) {
        return new AjaxResult<List<SysUserRole>>().success(sysUserRoleService.list(sysUserRole));
    }

    /**
     * 编辑用户角色
     * @param sysUserRole 用户角色信息
     */
    @OperateLog(title = "用户信息", businessType = "分配角色")
    @PermAuth("system:user:allocation")
    @PostMapping("/editUserRole")
    public AjaxResult<Void> editUserRole(@RequestBody SysUserRole sysUserRole) {
        sysUserRoleService.removeByUserId(sysUserRole.getUserId());
        boolean row = sysUserRoleService.editUserRole(sysUserRole);
        return row ? new AjaxResult<Void>().success() : new AjaxResult<Void>().error();
    }
}